<template>
	<view class="container">
		<view class="game-info">
			<text>当前玩家：{{ currentPlayer === 'B' ? '黑棋' : '白棋' }}</text>
			<text>剩余悔棋次数：{{ undoCount }}</text>
		</view>
		<view class="board">
			<view v-for="(row, rowIndex) in boardSize" :key="rowIndex" class="board-row">
				<view v-for="(col, colIndex) in boardSize" :key="colIndex" class="board-col" @click="placePiece(rowIndex, colIndex)">
					<view v-if="board[rowIndex][colIndex] === 'B'" class="piece black"></view>
					<view v-if="board[rowIndex][colIndex] === 'W'" class="piece white"></view>
				</view>
			</view>
		</view>
		<button @click="undoMove">悔棋</button>
	</view>
</template>

<script>
	export default {
		data () {
			return {
				boardSize: 15,
				board: [],
				currentPlayer: 'B',
				moveHistory: [],
				undoCount: 3,
			};
		},
		mounted () {
			this.initBoard();
		},
		methods: {
			initBoard () {
				this.board = Array(this.boardSize).fill().map(() => Array(this.boardSize).fill(''));
			},
			placePiece (row, col) {
				if (this.board[row][col] === '' && this.currentPlayer === 'B') {
					this.makeMove(row, col, this.currentPlayer);
					if (!this.checkForWin(row, col)) {
						this.currentPlayer = 'W';
						this.aiMove();
					}
				}
			},
			makeMove (row, col, player) {
				this.board[row][col] = player;
				this.moveHistory.push({ row, col, player });
				if (this.checkForWin(row, col)) {
					alert(`${player} wins!`);
					this.initBoard();
				}
			},
			aiMove () {
				let move = this.findBestMove();
				if (move) {
					this.makeMove(move.row, move.col, 'W');
				}
				this.currentPlayer = 'B';
			},
			findBestMove() {
			// 如果AI上一步已经有效地阻止了对手的连线，则考虑其他策略
			  if (this.lastMoveBlockedOpponent()) {
				// 可以是随机落子，或者在对手最后一步附近落子
				let lastMove = this.moveHistory[this.moveHistory.length - 1];
				if (lastMove) {
				  return this.findNearbyMove(lastMove.row, lastMove.col, 'W');
				}
				return this.randomMove();
			  }
			 
			
			  // 其次，阻止对手四子连线
			  let blockFourMove = this.findBlockMove('B', 4);
			  if (blockFourMove) {
			    return blockFourMove;
			  }
			
			  // 然后，阻止对手三子连线
			  let blockThreeMove = this.findBlockMove('B', 3);
			  if (blockThreeMove) {
			    return blockThreeMove;
			  }
			  
			  // AI自己的赢棋机会
			  let aiWinningMove = this.findWinningMove('W');
			  if (aiWinningMove) {
			    return aiWinningMove;
			  }
			
			  // 接着，尝试在对手最后一步附近落子
			  let lastMove = this.moveHistory[this.moveHistory.length - 1];
			  if (lastMove) {
			    return this.findNearbyMove(lastMove.row, lastMove.col, 'W');
			  }
			
			  // 最后，随机落子
			  return this.randomMove();
			},

			findWinningMove (player) {
				for (let i = 0; i < this.moveHistory.length; i++) {
					let move = this.moveHistory[i];
					if (move.player !== player) continue;

					let directions = [
						[1, 0],
						[0, 1],
						[1, 1],
						[-1, 1]
					];
					for (let [dRow, dCol] of directions) {
						if (this.checkLine(move.row, move.col, dRow, dCol, player) >= 3) {
							// 检查两端是否有空位
							if (this.isCellEmpty(move.row - dRow, move.col - dCol)) {
								return { row: move.row - dRow, col: move.col - dCol };
							}
							if (this.isCellEmpty(move.row + 3 * dRow, move.col + 3 * dCol)) {
								return { row: move.row + 3 * dRow, col: move.col + 3 * dCol };
							}
						}
					}
				}
				return null;
			},
			lastMoveBlockedOpponent() {
			  if (this.moveHistory.length > 0) {
			    let lastMove = this.moveHistory[this.moveHistory.length - 1];
			    if (lastMove.player === 'W') {
			      // 检查这一步之后，对手是否还有潜在的三子或四子连线
			      let blockThreeMove = this.findBlockMove('B', 3);
			      let blockFourMove = this.findBlockMove('B', 4);
			      if (!blockThreeMove && !blockFourMove) {
			        return true;
			      }
			    }
			  }
			  return false;
			},


			findBlockMove(player, lineLength) {
			  for (let i = 0; i < this.moveHistory.length; i++) {
			    let move = this.moveHistory[i];
			    if (move.player !== player) continue;
			
			    let directions = [[1, 0], [0, 1], [1, 1], [-1, 1]];
			    for (let [dRow, dCol] of directions) {
			      if (this.checkLine(move.row, move.col, dRow, dCol, player) === lineLength - 1) {
			        // 检查两端是否有空位
			        if (this.isCellEmpty(move.row - dRow, move.col - dCol)) {
			          return { row: move.row - dRow, col: move.col - dCol };
			        }
			        if (this.isCellEmpty(move.row + lineLength * dRow, move.col + lineLength * dCol)) {
			          return { row: move.row + lineLength * dRow, col: move.col + lineLength * dCol };
			        }
			      }
			    }
			  }
			  return null;
			},

			findNearbyMove (row, col, player) {
				let directions = [
					[1, 0],
					[0, 1],
					[1, 1],
					[-1, 1],
					[-1, 0],
					[0, -1],
					[-1, -1],
					[1, -1]
				];
				for (let [dRow, dCol] of directions) {
					let newRow = row + dRow;
					let newCol = col + dCol;
					if (this.isCellEmpty(newRow, newCol)) {
						return { row: newRow, col: newCol };
					}
				}
				return null;
			},
			isCellEmpty (row, col) {
				return row >= 0 && row < this.boardSize && col >= 0 && col < this.boardSize && this.board[row][col] === '';
			},
			randomMove () {
				let emptyCells = [];
				for (let row = 0; row < this.boardSize; row++) {
					for (let col = 0; col < this.boardSize; col++) {
						if (this.isCellEmpty(row, col)) {
							emptyCells.push({ row, col });
						}
					}
				}
				if (emptyCells.length > 0) {
					return emptyCells[Math.floor(Math.random() * emptyCells.length)];
				}
				return null;
			},
			checkForWin (row, col) {
				let directions = [
					[1, 0],
					[0, 1],
					[1, 1],
					[-1, 1]
				];
				for (let [dRow, dCol] of directions) {
					if (this.checkLine(row, col, dRow, dCol, this.board[row][col]) >= 5) {
						return true;
					}
				}
				return false;
			},
			checkLine (row, col, dRow, dCol, player) {
				let total = 1; // 包括当前位置的棋子
				for (let i = 1; i < 5; i++) {
					if (this.getCell(row + i * dRow, col + i * dCol) === player) {
						total++;
					} else {
						break;
					}
				}
				for (let i = 1; i < 5; i++) {
					if (this.getCell(row - i * dRow, col - i * dCol) === player) {
						total++;
					} else {
						break;
					}
				}
				return total;
			},
			getCell (row, col) {
				if (row >= 0 && row < this.boardSize && col >= 0 && col < this.boardSize) {
					return this.board[row][col];
				}
				return null;
			},
			undoMove () {
				if (this.undoCount > 0 && this.moveHistory.length > 0) {
					let lastMove = this.moveHistory.pop();
					this.board[lastMove.row][lastMove.col] = '';
					this.undoCount--;
					this.currentPlayer = lastMove.player === 'B' ? 'W' : 'B';
				} else {
					alert('无法悔棋！');
				}
			},
		}
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
	}

	.game-info {
		margin-bottom: 10px;
	}

	.board {
		display: grid;
		grid-template-columns: repeat(15, 1fr);
		width: 90vw;
		height: 90vw;
		border: 5px solid #764c24;
		background-image: url('../../static/goBangBg.jpg');
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
	}

	.board-row {
		/* display: flex; */
		width: 100%;
		border: 1px solid #ddd;
	}

	.board-col {
		border: 1px solid #ddd;
		position: relative;
		aspect-ratio: 1;
	}

	.piece {
		position: absolute;
		top: 50%;
		left: 50%;
		width: 80%;
		height: 80%;
		border-radius: 50%;
		transform: translate(-50%, -50%);
	}

	.black {
		background-color: #000;
	}

	.white {
		background-color: #fff;
	}
</style>